#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#define COMMEND_SIZE 1024
#define FORMAT "[%s%s %s]#"
using namespace std;
#define N 128 
char* g_argv[N];
int g_argc;

const char* GetUserName()
{
	const char* username = getenv("USER");
	return username == NULL?"None":username;
}

const char* GetHostName()
{
	const char* hostname = getenv("HOSTNAME");
	return hostname == NULL?"None":hostname;
}

const char* GetPwd()
{
	const char* pwd = getenv("PWD");
	return pwd == NULL?"None":pwd;
}

void MakeCommendPrompt(char cmd_prompt[],int size)
{
	snprintf(cmd_prompt,size,FORMAT,GetUserName(),GetHostName(),GetPwd());
}

void PrintPrompt()
{
	char buffer[COMMEND_SIZE];
	MakeCommendPrompt(buffer,sizeof(buffer));
	printf("%s",buffer);
	fflush(stdout);
}

bool GetCommendLine(char* out,int size)
{
	char* c = fgets(out,size,stdin);
	if(c==NULL) return false;
	out[strlen(out)-1]=0;
	if(strlen(out)==0) return false;
	return true;
}

bool CommendParse(char* commandline)
{
	g_argc = 0;
	g_argv[g_argc++] = strtok(commandline," ");
	while((bool)(g_argv[g_argc++]=strtok(nullptr," ")));
	g_argc--;
	return true;
}

void PrintArgv()
{
	for(int i=0;g_argv[i];i++)
	{
		printf("argv[%d]->%s\n",i,g_argv[i]);
	}
	printf("g_argc:%d\n",g_argc);
}

int Execute()
{
	pid_t id=fork();
	if(id==0)
	{
		execvp(g_argv[0],g_argv);
		exit(1);
	}
	pid_t rid = waitpid(id,nullptr,0);
	(void)rid;
	return 0;
}

int main()
{
	while(true){
	//1.命令行回显
	PrintPrompt();
	//2.获取用户命令
	char commendline[COMMEND_SIZE];
	if(!GetCommendLine(commendline,sizeof(commendline)))
		continue;
	CommendParse(commendline);
	Execute();
	
	}
	return 0;
}
